package org.example.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.example.common.exception.MyExampleException;
import org.example.common.lang.AjaxResult;
import org.example.common.lang.Result;
import org.example.common.utils.StringUtils;
import org.example.common.utils.UploadUtils;
import org.example.model.User;
import org.example.service.ExcelImportService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.MessageUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "") Integer current,@RequestParam(defaultValue = "") Integer size){
        List<User> list = userService.list(current,size);
        if(list.size() <= 0){
            throw new MyExampleException("当前没有用户信息");
        }
        return Result.success(list);
    }

    @GetMapping("/findById")
    public Result findById(Integer id){
        return Result.success(userService.findById(id));
    }

    @PostMapping("/addUser")
    public Result addUser(User user){
        return Result.success(userService.addUser(user));
    }

    @GetMapping("/delById")
    public Result delById(Integer id){
        return Result.success(userService.delById(id));
    }

    @GetMapping("/updateById")
    public Result updateById(User user){
        return Result.success(userService.updateById(user));
    }

    @GetMapping("/selectList")
    public Result selectList(@RequestParam(defaultValue = "1") Integer current,@RequestParam(defaultValue = "10") Integer size,@Param("username") String username,@Param("age") Integer age){
        List<User> list = userService.selectList(current,size,username,age);
        if(list.size() <= 0){
            throw new MyExampleException("当前没有用户信息");
        }
        return Result.success(list);
    }

    @GetMapping("/delByIds/{ids}")
    public Result deleteByIds(@PathVariable("ids") String ids){
        List<Integer> delIds = new ArrayList<>();
        if(ids.contains(",")){
            String[] strIds = ids.split(",");
            for(String strId : strIds){
                delIds.add(Integer.parseInt(strId));
            }
            userService.deleteByIds(delIds);
        }else{
            delIds.add(Integer.parseInt(ids));
            userService.deleteByIds(delIds);
        }
        return Result.success();
    }

    @PostMapping("/addUsers")
    public Result addUsers(@RequestBody List<User> userList){
        return Result.success(userService.insertList(userList));
    }

    @Autowired
    private ExcelImportService excelImportService;
    @PostMapping("/import")
    public Result importUsers(@RequestParam("file") MultipartFile multipartFile){
        String result;
        try {
            File file = File.createTempFile("temp",null);
            multipartFile.transferTo(file);
            List<User> users = excelImportService.importUsers(file);

            System.out.println(users);


            userService.insertList(users);


            result = "导入成功";
        }catch (Exception e){
            e.printStackTrace();
            result =  "导入失败";
        }

        return Result.success(result);
    }

    @GetMapping("/export")
    public Result exportUsers(HttpServletResponse request){
        List<User> userList = userService.listAll();
        userService.exportUsersToExcel(userList,request);
        return null;
    }

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("id") Integer id,@RequestParam("file") MultipartFile file, HttpServletRequest request){

        String filePath = request.getServletContext().getRealPath("/")+"/resources/upload/";
        String path = "";
        try{
            if(file != null){
                path = UploadUtils.fileUpload(file,filePath);
            }
        }catch (IOException e){
            return AjaxResult.error(e.getMessage());
        }
        //System.out.println(request.getServletContext().getContextPath()+"/resources/upload/"+path);
        System.out.println(StringUtils.isEmpty(path));
        if(!StringUtils.isEmpty(path)){
            //request.getServletContext().getContextPath()+"/R"
            //request.getServletContext().getContextPath()+"/resources/upload/"+path
        }
        System.out.println("cccc:"+id+"----"+path);
        userService.uploadImg(id,path);
        return AjaxResult.success("上传成功",path);
    }
    @PostMapping("/download")
    public String downloads(HttpServletResponse response,HttpServletRequest request) throws Exception{
        String path = request.getServletContext().getRealPath("/resources/upload");
        String fileName = "组 1_1713492717828.png";

        //设置response响应头
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition","attachment;fileName="+URLEncoder.encode(fileName,"UTF-8"));

        File file = new File(path,fileName);
        InputStream input = new FileInputStream(file);
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        while ((index = input.read(buff)) != -1){
            out.write(buff,0,index);
            out.flush();
        }

        out.close();
        input.close();
        return null;
    }


}

































